(function ($) {

    var form = $('#task');

    $('#store_address').autocomplete({
        lookup: (function () {
            var s = [];
            STORE_LIST.forEach(function (item) {
                s.push({value: ' ' + item.title, data: item.id});
            });
            return s;
        })(),
        onSelect: function (suggestion) {
            $('#store_address').val($.trim(suggestion.value));
            form.find('[name="store_id"]').val(suggestion.data);
        }
    });

    $('#upload').on('click', function (e) {
        e.preventDefault();

        var data = {}
        form.serializeArray().forEach(function (item) {
            data[item['name']] = item['value'];
        });

        data.image = form.find('[name="image"]').val();

        if (!data.store_id) {
            form.find('.js-store').addClass('error');
            return false;
        }

        if (!data.image) {
            form.find('.js-image').addClass('error');
            return false;
        }

        form.submit();
    });

    $('#task input').focus(function () {
        $(this).parent('.field').removeClass('error');
    });

    form.find('[name="image"]').on('change', function () {
        var image = $(this).get(0).files[0];
        var reader = new FileReader();
        reader.onloadend = function () {
            form.find('[name="image_data"]').val(reader.result.split(',')[1]);
        }
        if (image) {
            reader.readAsDataURL(image);
        } else {
            form.find('[name="image_data"]').val('');
        }
    });
})(jQuery);